package com.zmn.oms.zmn.normal.business.impl.order.advancequote;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.dro.phenomenon.PhenomenonDRO;
import com.zmn.base.common.data.dubbo.interfaces.tags.TagsListRemoteService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.base.price.common.dto.fixed.*;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.base.price.common.dto.item.ItemPriceQuery;
import com.zmn.base.price.common.dto.item.ItemSimpleDRO;
import com.zmn.base.price.dubbo.interfaces.calculate.FixedFlowRemoteService;
import com.zmn.base.price.dubbo.interfaces.calculate.ItemPriceRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.entity.advancequote.AdvanceQuoteBaseQuery;
import com.zmn.oms.model.entity.advancequote.AdvanceQuoteItemQuery;
import com.zmn.oms.model.entity.advancequote.AdvanceQuotePhenQuery;
import com.zmn.oms.model.vo.order.advanceQuote.CategVO;
import com.zmn.oms.model.vo.order.advanceQuote.ProductVO;
import com.zmn.oms.zmn.normal.business.interfaces.order.advancequote.AdvanceQuoteListBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author sunlife
 * @date:2022/9/22 下午8:07
 * description: 提前报价相关基础接口
 */
@Service
@Slf4j
public class AdvanceQuoteListBServiceImpl implements AdvanceQuoteListBService {


    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private TagsListRemoteService tagsListRemoteService;
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private FixedFlowRemoteService fixedFlowRemoteService;
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ItemPriceRemoteService itemPriceRemoteService;

    private static final String TAG = "下单查询";

    // 排除的服务项ID
    // 3003  其他
    //1003  材料费
    //1001  其他服务
    //1004  增值服务
    //1021  材料收费
    //1019  其他服务项
    //1020  产品销售
    //1043  附加服务
    //3007  增值产品
    //3008  其他收费
    private static final List<Integer> EXCLUED_ITEM_TYPE_ID = Lists.newArrayList(3003, 1003, 1001, 1004, 1021, 1019, 1020, 1043, 3007, 3008);

    @Override
    public List<KVDict> listFaultPhen(AdvanceQuoteBaseQuery query) {
    FixedPhenomenonQuery phenQuery = FixedPhenomenonQuery.builder()
            .bizType(query.getBizType())
            .channelId(query.getChannelId())
            .cityId(query.getCityId())
            .ecProductId(query.getShowProductId())
            .tariffId(query.getTariffId())
            .flag(true)
            .build();
        log.info("[{}]查询故障现象 入参：{}", TAG, JSON.toJSONString(phenQuery));
        ResponseDTO<List<PhenomenonDRO>> responseDTO = fixedFlowRemoteService.listFixedPhenoByQuery(phenQuery);
        log.info("[{}]查询故障现象 出参：{}", TAG, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            log.info("获取故障现象失败: {}", responseDTO.getMessage());
            return Lists.newArrayList();
        }

        List<KVDict> phenList = Lists.newArrayList();
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            phenList = responseDTO.getData().stream()
                    .sorted(Comparator.comparing(PhenomenonDRO::getSort))
                    .map(phen -> KVDict.builder().value(phen.getPhenId()).text(phen.getPhenName()).build())
                    .collect(Collectors.toList());
        }
        return phenList;
    }

    @Override
    public List<CategVO> listProductCateg(AdvanceQuotePhenQuery query) {
        FixedErpCategFilterPhenoQuery phenQuery = FixedErpCategFilterPhenoQuery.builder()
                .bizType(query.getBizType())
                .channelId(query.getChannelId())
                .cityId(query.getCityId())
                .ecProductId(query.getShowProductId())
                .phenomenonId(query.getPhenId())
                .brandId(query.getBrandId())
                .build();
        log.info("[{}]故障现象查询后台二级分类 入参：{}", TAG, JSON.toJSONString(phenQuery));
        ResponseDTO<List<FixedCategFomOmsDRO>> responseDTO = fixedFlowRemoteService.listErpCategFilterPhenoForOmsByQuery(phenQuery);
        log.info("[{}]故障现象查询后台二级分类 出参：{}", TAG, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            log.info("获取后台产品二级分类失败: {}", responseDTO.getMessage());
            return Lists.newArrayList();
        }

        List<CategVO> categList = Lists.newArrayList();
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            categList = responseDTO.getData().stream()
                    .sorted(Comparator.comparing(FixedCategFomOmsDRO::getCategId))
                    .map(categ -> CategVO.builder()
                            .categId(categ.getCategId())
                            .categName(categ.getCategName())
                            .minPrice(categ.getLowerPrice())
                            .maxPrice(categ.getUpperPrice())
                            .build())
                    .collect(Collectors.toList());
        }

        return categList;
    }

    @Override
    public List<ProductVO> listProduct(AdvanceQuotePhenQuery query) {
        FixedErpProductQuery2 productQuery = FixedErpProductQuery2.builder()
                .bizType(query.getBizType())
                .channelId(query.getChannelId())
                .cityId(query.getCityId())
                .ecProductId(query.getShowProductId())
                .phenomenonId(query.getPhenId())
                .categId(query.getCategId())
                .brandId(query.getBrandId())
                .flag(true)
                .build();
        log.info("[{}]故障现象查询后台产品 入参：{}", TAG, JSON.toJSONString(productQuery));
        ResponseDTO<List<FixedErpProductDRO>> responseDTO = fixedFlowRemoteService.listErpProductFilterPhenoByQuery(productQuery);
        log.info("[{}]故障现象查询后台产品 出参：{}", TAG, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            log.info("获取故障现象失败: {}", responseDTO.getMessage());
            return Lists.newArrayList();
        }

        List<ProductVO> productList = Lists.newArrayList();
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            // 处理产品数据
            productList = responseDTO.getData().stream()
                    .sorted(Comparator.comparing(FixedErpProductDRO::getSort))
                    .map(product -> {
                        ProductVO productVO = ProductVO.builder()
                                .productId(product.getProductId())
                                .productName(product.getProductName())
                                .tariffName(product.getTariffName())
                                .build();
                        if (CollectionUtil.isNotNullOrEmpty(product.getItemDROList())) {
                            Optional<ItemSimpleDRO> itemOptional = product.getItemDROList().stream()
                                    .filter(item -> Objects.nonNull(item.getPrice()))
                                    .min(Comparator.comparing(ItemSimpleDRO::getPrice));
                            if (itemOptional.isPresent()) {
                                ItemSimpleDRO itemDRO = itemOptional.get();
                                productVO.setPrice(itemDRO.getPrice());
                                productVO.setItemId(itemDRO.getItemId());
                            }
                        }
                        return productVO;
                    })
                    .filter(productVO -> NumberUtil.isNotNullOrZero(productVO.getPrice()))
                    .collect(Collectors.toList());
        }
        return productList;
    }

    @Override
    public List<KVDict> listServiceItem(AdvanceQuoteBaseQuery query) {
        ItemPriceQuery itemQuery = ItemPriceQuery.builder()
                .bizType(query.getBizType())
                .channelId(query.getChannelId())
                .cityId(query.getCityId())
                .productId(query.getShowProductId())
                .showType(BaseProductConsts.EC_SHOW_TYPE)
                .build();

        log.info("[{}]查询服务项 入参：{}", TAG, JSON.toJSONString(itemQuery));
        ResponseDTO<List<ItemDRO>> responseDTO = itemPriceRemoteService.listItemPriceByQuery(itemQuery);
        log.info("[{}]查询服务项 出参：{}", TAG, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            log.info("获取服务项列表失败: {}", responseDTO.getMessage());
            return Lists.newArrayList();
        }

        List<KVDict> itemList = Lists.newArrayList();
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            itemList = responseDTO.getData().stream()
                    .filter(item -> Objects.nonNull(item.getPrice()) && !EXCLUED_ITEM_TYPE_ID.contains(item.getItemTypeId()))
                    .sorted(Comparator.comparing(ItemDRO::getSort))
                    .map(item -> KVDict.builder().value(item.getItemId()).text(item.getItemName()).build())
                    .distinct()
                    .collect(Collectors.toList());
        }
        return itemList;
    }

    @Override
    public List<CategVO> listProductCategWithItemId(AdvanceQuoteItemQuery query) {
        FixedErpCategItemQuery itemQuery = FixedErpCategItemQuery.builder()
                .bizType(query.getBizType())
                .channelId(query.getChannelId())
                .cityId(query.getCityId())
                .ecProductId(query.getShowProductId())
                .itemId(query.getItemId())
                .brandId(query.getBrandId())
                .build();
        log.info("[{}]服务项查询后台产品二级分类 入参：{}", TAG, JSON.toJSONString(itemQuery));
        ResponseDTO<List<FixedCategFomOmsDRO>> responseDTO = fixedFlowRemoteService.listErpCategFilterItemByQuery(itemQuery);
        log.info("[{}]服务项查询后台产品二级分类 出参：{}", TAG, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            log.info("获取后台产品二级分类失败: {}", responseDTO.getMessage());
            return Lists.newArrayList();
        }

        List<CategVO> categList = Lists.newArrayList();
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            categList = responseDTO.getData().stream()
                    .sorted(Comparator.comparing(FixedCategFomOmsDRO::getCategId))
                    .map(categ -> CategVO.builder()
                            .categId(categ.getCategId())
                            .categName(categ.getCategName())
                            .minPrice(categ.getLowerPrice())
                            .maxPrice(categ.getUpperPrice())
                            .build())
                    .collect(Collectors.toList());
        }
        return categList;
    }

    @Override
    public List<ProductVO> listProductWithItem(AdvanceQuoteItemQuery query) {
        FixedErpProductItemQuery itemQuery = FixedErpProductItemQuery.builder()
                .bizType(query.getBizType())
                .channelId(query.getChannelId())
                .cityId(query.getCityId())
                .ecProductId(query.getShowProductId())
                .itemId(query.getItemId())
                .categId(query.getCategId())
                .brandId(query.getBrandId())
                .build();
        log.info("[{}]服务项查询后台产品 入参：{}", TAG, JSON.toJSONString(itemQuery));
        ResponseDTO<List<FixedErpProductFilterItemDRO>> responseDTO = fixedFlowRemoteService.listErpProductFilterItemByQuery(itemQuery);
        log.info("[{}]服务项查询后台产品 出参：{}", TAG, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            log.info("获取产品失败: {}", responseDTO.getMessage());
            return Lists.newArrayList();
        }

        List<ProductVO> productList = Lists.newArrayList();
        if (CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
            // 处理产品数据
            productList = responseDTO.getData().stream()
                    .sorted(Comparator.comparing(FixedErpProductFilterItemDRO::getSort))
                    .map(product -> {
                        ProductVO productVO = ProductVO.builder()
                                .productId(product.getProductId())
                                .productName(product.getProductName())
                                .tariffName(product.getTariffName())
                                .build();
                        if (CollectionUtil.isNotNullOrEmpty(product.getItemDROList())) {
                            Optional<ItemSimpleDRO> itemOptional = product.getItemDROList().stream()
                                    .filter(item -> Objects.equals(item.getItemId(), query.getItemId())).findFirst();
                            if (itemOptional.isPresent()) {
                                ItemSimpleDRO itemDRO = itemOptional.get();
                                productVO.setPrice(itemDRO.getPrice());
                                productVO.setItemId(itemDRO.getItemId());
                            }
                        }
                        return productVO;
                    })
                    .filter(productVO -> NumberUtil.isNotNullOrZero(productVO.getPrice()))
                    .collect(Collectors.toList());
        }
        return productList;
    }
}
